package C040;

/**
 * ClassName: C02
 * Package: C040
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/1 22:09
 * @Version 1.0
 * @Since 1.0
 */
public class C02 {
    public static void main(String[] args) {
        System.out.println(totalNQueens(14));
    }

    public static int totalNQueens(int n) {
        int limit = (1 << n) - 1;
        return process(limit, 0, 0, 0);
    }

    /**
     * 位运算解决N皇后的问题
     *
     * @param limit 几个皇后，这个limit就有几个1
     * @param col   列的设置(已经设置了几个列)
     * @param left  列的左边的限制
     * @param right 列的右边的限制
     * @return
     */
    public static int process(int limit, int col, int left, int right) {
        if (limit == col) {
            return 1;
        }

        // 可用的位1，不可用的位0
        int useBit = ~(col | left | right) & limit;
        int place = 0;
        int res = 0;
        while (useBit != 0) {
            place = useBit & -useBit;
            useBit ^= place;
            res += process(limit, col | place, (left | place) << 1, (right | place) >> 1);
        }
        return res;
    }
}
